package bold.module.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Before;
import org.junit.Test;

public class CuratorLock {
    CuratorFramework curatorFramework;

    @Before
    public void init() {
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .connectionTimeoutMs(15 * 1000) //连接超时时间，默认15秒
                .sessionTimeoutMs(60 * 1000) //会话超时时间，默认60秒   todo 这个时间就是 临时节点的删除时间
//                .namespace("arch") //设置命名空间
                .build();
        curatorFramework.start();
    }

    @Test
    public void lock1() throws Exception {
        InterProcessMutex interProcessMutex = new InterProcessMutex(curatorFramework, "/lock");
        interProcessMutex.acquire();
        interProcessMutex.acquire();
        System.err.println("获取锁");
        Thread.sleep(1000L*10);
        interProcessMutex.release();

    }

    //不可重入
    @Test
    public void lock2() throws Exception {
        InterProcessSemaphoreMutex interProcessMutex = new InterProcessSemaphoreMutex(curatorFramework, "/lock");
        interProcessMutex.acquire();
        System.err.println("获取锁1");
        interProcessMutex.acquire();
        System.err.println("获取锁2");
        Thread.sleep(1000L*10);
        interProcessMutex.release();

    }





}
